#include "beidouportobject.h"
#include "beidouportobject.h"
#include "beidouportobject.h"



#include <QThread>
#include <QDebug>
#include <QThread>
#include <QDateTime>


BeidouObject::BeidouObject(QObject *parent) : QObject(parent)
{

}

BeidouObject::BeidouObject(QString COMname)
{
    this->COMName = COMname;
    initialize_port_start_thread(COMName);
}

BeidouObject::~BeidouObject()
{

}

void BeidouObject::initialize_port_start_thread(QString COMName){
    my_thread = new QThread();
    myPort = new QSerialPort();

    timerReadAll = new QTimer();

    init_port(COMName);

    this->moveToThread(my_thread);
    myPort->moveToThread(my_thread);
    timerReadAll->moveToThread(my_thread);

    my_thread->start();  //启动线程
}

void BeidouObject::init_port(QString COMName)
{

    //myPort->setPortName("COM19");
    myPort->setPortName(COMName);
    //port->setPortName("/dev/ttyS1");                   //串口名 windows下写作COM1

    myPort->setBaudRate(9600);                           //波特率

    myPort->setDataBits(QSerialPort::Data8);             //数据位

    myPort->setStopBits(QSerialPort::OneStop);           //停止位

    myPort->setParity(QSerialPort::NoParity);            //奇偶校验

    myPort->setFlowControl(QSerialPort::NoFlowControl);  //流控制

    if(myPort->isOpen())//如果串口已经打开了 先给他关闭了
    {
        myPort->clear();
        myPort->close();
    }

    if (myPort->open(QIODevice::ReadWrite))
    {
        qDebug() << "Port have been opened";
    }
    else
    {
        qDebug() << "Failed to Open"<<COMName;
    }

    // QSerialPort(串口)对象信号转BeidouObject(北斗)对象的槽函数处理
    connect(myPort, SIGNAL(readyRead()), this, SLOT(handle_data()), Qt::QueuedConnection); //Qt::DirectConnection

    connect(timerReadAll, SIGNAL(timeout()), this, SLOT(timeUpdateReadAll()));

    connect(this, &BeidouObject::send_data, this, &BeidouObject::write_data);//,Qt::QueuedConnection
    connect(this, &BeidouObject::signal_stop, this ,& BeidouObject::slot_stop);

}


void BeidouObject::handle_data()
{

    timerReadAll->start(200);                  //启动定时器，接收100毫秒数据（根据情况设定）
    revBuffer.append( myPort->readAll());
}

void BeidouObject::timeUpdateReadAll()
{
    timerReadAll->stop();
    if(revBuffer.length()!=0)
    {

        qDebug() << QStringLiteral("data received(收到的数据):") << revBuffer;
        qDebug() << "BeidouObject receive thread:" << QThread::currentThread()<<",pid "<<QThread::currentThreadId();

        emit receive_data(revBuffer.toLatin1());

        analyseData(revBuffer);

        wakeup_mutex();

    }
    revBuffer.clear();
}

void BeidouObject::wakeup_mutex(){
    mutex.lock();
    waitCon.wakeAll();
    mutex.unlock();
}

void BeidouObject::analyseData(QString revBuffer){

    QStringList result;
    QStringList  strs =revBuffer.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);

    foreach (QString response, strs)
    {
        if(response.contains("GGA")){

            QStringList items=  response.split(",");

            for (int i=0;i<items.size();i++) {
                result.append( items.at(i));
            }
        }

    }

    qDebug() <<"ANALYSE:" << result;

    emit transfer_result(result);
}



void BeidouObject::write_data(QString send_data)
{
    qDebug() << "port write data Id is:" << QThread::currentThreadId();

    send_data+="\r";
    qDebug() <<send_data;
    myPort->write(send_data.toLocal8Bit());   //发送“data”字符

}

bool BeidouObject::func_stop(unsigned long mytime){

    bool res = false;
    qDebug() << "func_stop  thread  is" << QThread::currentThread()
             <<",pid is  "<<QThread::currentThreadId();
    qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]")<< "wakeup  wait mutex";



    if(my_thread!=nullptr ){

        res =my_thread->wait(mytime);
        qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]")
                 << "beidou thread wait() =  "<<res;
        qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]")
                 << "isFinished():"<<my_thread->isFinished();
        qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]")
                 << "isRunning():"<<my_thread->isRunning();

        my_thread->deleteLater();
        delete my_thread;
        my_thread= nullptr;


       // qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]")<< "Stoped BD Port！";
    }


    return  res;

}




void BeidouObject::slot_stop()
{
   // qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]")<< "wakeup  wait mutex";

    qDebug() << "slot_stop thread is" << QThread::currentThread()
             <<",pid is "<<QThread::currentThreadId();

    wakeup_mutex();

    if(myPort!=nullptr){
        qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]")<< "Closing BD Port ……";
        myPort->clear();
        myPort->close();
        myPort->deleteLater();
        myPort = nullptr;
        qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]")<< "Closed BD Port";

    }



    if(my_thread!=nullptr ){

        //my_thread->requestInterruption();
        my_thread->quit();  //my_thread->exit(0);
        qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]")
                 <<" thread::quit() be called.";
    }



}


